package com.example.employeemanagement.Controller;

import com.example.employeemanagement.dto.UploadAvatarDto;
import com.example.employeemanagement.service.FileService;
import com.example.employeemanagement.vo.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上传控制器
 * 处理文件上传相关请求
 */
@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 上传用户头像
     * 
     * @param file 头像文件
     * @param employeeId 员工ID
     * @return 上传结果
     */
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<ApiResponse<String>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam("employeeId") Integer employeeId) {
        
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ResponseEntity.badRequest()
                        .body(new ApiResponse<>("ERROR", "只允许上传图片文件", null));
            }
            
            // 验证文件大小（限制为2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return ResponseEntity.badRequest()
                        .body(new ApiResponse<>("ERROR", "文件大小不能超过2MB", null));
            }
            
            // 上传文件
            String avatarPath = fileService.uploadAvatar(file, employeeId);
            
            return ResponseEntity.ok(new ApiResponse<>("SUCCESS", "头像上传成功", avatarPath));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>("ERROR", e.getMessage(), null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>("ERROR", "头像上传失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 访问头像文件
     * 
     * @param filename 文件名
     * @return 文件资源
     */
    @GetMapping("/avatar/view/{filename}")
    public ResponseEntity<Resource> viewAvatar(@PathVariable String filename) {
        try {
            // 构建文件路径 - 使用与 FileServiceImpl 相同的固定路径
            String avatarDir = "D:\\employee-avatars" + File.separator;
            Path filePath = Paths.get(avatarDir + filename);
            
            // 检查文件是否存在
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }
            
            // 创建文件资源
            Resource resource = new FileSystemResource(filePath.toFile());
            
            // 获取文件的MIME类型
            String contentType = Files.probeContentType(filePath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .body(resource);
                    
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}